<?php
namespace control;
/*
*节假日类
*/

class holidayClass  extends adIndexClass
{
    private const table = 'holiday';
    private const page = 'holiday';
    private const title = '节假日';

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "年份" =>
                        text(array("name" => "startDay", "laydate" => array("type" => "year"), "title" => "年份起")) . "\n-\n" .
                        text(array("name" => "endDay", "laydate" => array("type" => "year"), "title" => "年份止"))
                ]
            ]
        ],1);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /*查询*/
    public function home()
    {
        $html = $this->homeOptions(false);
        $url = root . "control/adIndex.html?cla=" . $this->get('cla') . "";
        $button = "<span class='spanButton' onclick=\"layer('".self::page."','edit')\">新增节假日</span>";
        //控件
        $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'name'      => [
                        'name'  => "名称",
                        'width' => 300,
                    ],
                    'year' => [
                        'name'  => "年份",
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'workDayNum'  => [
                        'name'  => "天数",
                        'width' => 300,
                    ],
                    'text'         => [
                        'name'  => "备注",
                        'width' => 300,
                    ],
                    'updateTime'          => [
                        'name'  => "更新时间",
                        'width' => 300,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }

    /*行政人事-节假日~列表页*/
    public function homeSearch()
    {
        //设置查询变量为空
        $where = "";
        if (!empty($this->post('startDay'))) {
            $where .= " and year >= '" . $this->post('startDay') . "' ";
        }
        if (!empty($this->post('endDay'))) {
            $where .= " and year <= '" . $this->post('endDay') . "' ";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'year desc,time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "workDayId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . $this->get('cla') . "";
        $workDayNumAll = 0;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = $this->dominate(array(
                "box" => array("name" => "workDayId", "value" => $array['id']),
                "detail" => array("title" => "节假日详情", "click" => "newIframe('节假日详情','" . root . "control/adIndex.html?cla=holiday&fun=detail&id=" . $array['id'] . "')"),
            ));
            $liButton[] = $dominate;
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "workDayNum":
                        $workDayNum = $array['workDay'] ? count(json_decode($array['workDay'], true)) : 0;
                        $workDayNumAll += $workDayNum;
                        $row[] = $workDayNum;
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton,"width" => 120),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 编辑
     * @return string
     */
    public function edit()
    {
        $info = query(self::table, " id = '" . $this->post('id') . "' ");
        //表单
        $html = $this->layerEdit([
            "table" => [
                [
                    must . "名称：" => text(array('name' => 'name', 'class' => 'text', 'value' => $info['name'])),
                    must . "年份：" => text(array('name' => 'year', 'class' => 'text', 'laydate' => ['type' => 'year'], 'value' => $info['year'])),
                ],
                [
                    "备注：" => textarea(array('name' => 'text', 'class' => 'textarea', 'value' => $info['text'])),
                ],
            ],
        ]);
        //返回
        return $this->layer(array("title" => L('job.button.editor').self::title, "height" => 250, "html" => $html));
    }

    /*编辑*/
    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        //赋值
        $field = array(
            "name" => $this->post('name'),
            "year" => $this->post('year'),
            "text" => $this->post('text'),//备注
        );
        $workDay = query(self::table, " id = '" . $id . "' ");
        //判断
       /* if (!$this->power(self::page, "edit")) {
            $json['warn'] = "权限不足";
        } else*/if (empty($field['name'])) {
            $json['warn'] = "请输入节假日名称";
        } elseif (empty($field['year'])) {
            $json['warn'] = "请输入年份";
        } elseif (sqlNum(self::table, " year = '$field[year]'  and id != '" . $this->post('id') . "' ") > 0) {
            $json['warn'] = "已存在此年份的节假日";
        } elseif (empty($workDay['id'])) {
            $field = array_merge($field, array("id" => $id, 'stid' =>' ', "time" => date("Y-m-d H:i:s")));
            $json['warn'] = insert(array("table" => self::table, "field" => $field));
        } else {
            $json['warn'] = update(array("table" => self::table, "field" => $field, "where" => "id = '$workDay[id]'"));
        }
        if (in_array($json['warn'], array("新增成功", "更新成功"))) {
            if ($json['warn'] == '新增成功') {
                //添加当前年份所有周末的日期
                $this->insertDay($field['year'], $this->post('id'));
            }
            //添加日志
            $type = mb_substr($json['warn'], 0, 2, 'utf-8');
            $text = $type . "了节假日：" . $field['name'] . "；年份：{$field['year']}，备注：" . $field['text'];
            $this->logText(array("type" => self::page, "text" => $text));
            //返回
            $_SESSION['warn'] = $json['warn'];
            $json['warn'] = 2;
        }
        $json['href'] = root . "control/adIndex.html?cla=holiday&fun=detail&id=" . $id;
        return json_encode($json, 320);
    }

    public function detailEdit()
    {
        $id = $this->post('id');
        //赋值
        $field = array(
            "workDay" => $_POST['holiday'],//节假日
        );
        $workDay = query(self::table, " id = '" . $id . "' ");
        //判断
        /*if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你还没有编辑权限";
        } else*/if (empty($workDay['id'])) {
            $json['warn'] = '未找到此节假日';
        } else {
            $workDays = $field['workDay']?json_decode($field['workDay'],true):[];
            $festivals = $workDay['festival']?json_decode($workDay['festival'],true):[];
            $festivalDate = array_keys($festivals);
            foreach ($festivalDate as $val){
                if (!in_array($val,$workDays)){
                    unset($festivals[$val]);
                }
            }
            $field['festival'] = json_encode($festivals,320);
            $json['warn'] = update(array("table" => self::table, "field" => $field, "where" => "id = '$workDay[id]'"));
        }
        if (in_array($json['warn'], array("新增成功", "更新成功"))) {
            //添加日志
            $type = mb_substr($json['warn'], 0, 2, 'utf-8');
            $text = $this->control['name'] . $type . "了节假日：" . $workDay['name'] . "；年份：{$workDay['year']}，id：" . $workDay['id'];
            $this->logText(array("type" => "workDay", "text" => $text));
            //返回
            $_SESSION['warn'] = $json['warn'];
            $json['warn'] = 2;
        }
        $json['href'] = root . "control/adIndex.html?cla=" . self::page . "&fun=detail&id=" . $id;
        return json_encode($json, 320);
    }

    /*行政人事-节假日~编辑页*/
    public function detail(): string
    {
        //定义参数
        if (empty($this->get('id'))) {
            $html = '未找到此' . self::title;
        } else {
            $workDay = query(self::table, " id = '" . $this->get('id') . "' ");
            if (empty($workDay['id'])) {
                $html = "未找到此记录";
            } else {
                $data = array("id" => $workDay['id'], "title" => $workDay['name'], "button" => "更新");
                $button = [];
//                if ($this->power(self::page, "edit")) {
                    $button[] = [
                        "name" => "保存",
                        "type" => "点击事件",
                        "cla" => $this->get('cla'),
                        "fun" => "commitData()",
                        "post" => ["id" => $this->get('id')],
                        'style' => 'li-btn-blue-bg',
                    ];
                    //按钮
                    $button[] = [
                        "name" => "编辑",
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "edit",
                        "post" => ["id" => $workDay['id']],
                    ];

//                }
//                if ($this->power(self::page, 'del')) {
                    //按钮
                    $button[] = [
                        "name" => "删除",
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "operate",
                        "post" => ["act" => 'del', "id" => $workDay['id']],
                    ];
//                }


                $tempHtml = '';
                for ($i = 0; $i < 12; $i++) {
                    $tempHtml .= "<li>
                                  <div class='dateTitle'>{{dateTitle[$i]}}</div>
                                  <calendar ref=\"calendar\" class='calendarD' v-on:date-db-click='dateChange'  multiple :select-date=\"date\" :show-title='false' :default-date='nowDate[$i]' :show-term='false' :show-festival='true' :show-lunar='false'>
                                   <template slot=\"dateCell\" slot-scope=\"{date}\">
                                      <el-popover>
                                        <dl>
                                         <dd><span class='hide-date hidden'>{{date.year}}-{{date.month<10?'0'+date.month:date.month}}-{{date.day<10?'0'+date.day:date.day}}</span></dd>
                                        </dl>
                                        <span slot=\"reference\" class=\"obj\"></span>
                                      </el-popover>
                                    </template>
                                    </calendar>
                                  </li>
                                ";
                }

                $workDayAllLi = "
                 <style>
            [v-cloak] {
                            display: none !important;
                        }
</style>
              <div id=\"app\" v-cloak>
              <ul>
                 {$tempHtml}
                </ul>
            </div>";

                $workDayNum = $workDay['workDay']?count(json_decode($workDay['workDay'], true)):0;
                $festivalNum = $workDay['festival']?count(json_decode($workDay['festival'], true)):0;
                $data['button'] = $this->tableShowButton($button);
                $data['html'] = $this->tableShow(array(
                    "基本信息" => array(
                        array(
                            "名称" => $workDay['name'],
                            "年份" => $workDay['year'],
                            "天数"=>"节假日总天数(包含周末)：".$workDayNum."天，其中节日放假：".$festivalNum.'天',
                            "创建人" => self::findStaff($workDay['stid']),
                        ),
                        array(
                            "创建时间" => $workDay['time'],
                            "更新时间" => $workDay['updateTime'],
                            "说明"=>"<p>1、右键点击设置每年的法定节假日</p><p>2、左键点击设置取消某一天是否为节假日</p>"
                        ),
                        array(
                            "备注" => pre($workDay['text']),
                        )
                    ),
                ));
                $data['html'] .= "<div class='tableShow'>
                                <div class='small-title'>选择节假日</div>
                                <form name='detailForm'>" . hidden(array('name' => 'id', 'value' => $workDay['id'])) . "<ul class='square'>" . $workDayAllLi . "</ul></form>
                            </div>";
                $data['html'] .= "
                  <link type=\"text/css\" href=\"" . root . "static/stylesheet/calendar.css?v=" . version . "\" rel=\"stylesheet\" />
             <script src=\"" . root . "static/javascript/vue.min.js?v=" . version . "\"></script>
            <script src='" . root . "static/javascript/calendar.umd.js?v=" . version . "'></script>
            <script>
//           document.oncontextmenu = function(a){
//               a.preventDefault();
//               return false;
//           }
$(document).contextmenu(function (e) {
    console.log(12)
    
  var event = e || window.event;
  if (event.preventDefault) {
    event.preventDefault(); // 防止浏览器默认行为(W3C)
  } else {
    event.returnValue = false; // IE中阻止浏览器行为
  }
  console.log(13)
});
              $(function() {
                 
                 let id = $('[name=id]').val();
                $.post(root+'control/adIndex.html?cla=holiday&fun=getDay',{id:id},function(res) {
                     window.app = new Vue({
                        el: '#app',
                        data: {
                          date: res.data.showDate,
                          nowDate:res.data.nowDate,
                          dateTitle:res.data.dateTitle
                        },
                        methods:{
                            dateChange:function (obj){
                                let d = new Date(obj.date)
                                let formatDate = d.getFullYear() + '-' + this.p(d.getMonth() + 1) + '-' + this.p(d.getDate());
                                layer('holiday','setting',{id:id,date:formatDate,lunarFestival:obj.lunarFestival,festival:obj.festival})
                                console.log(11)
                                
                            },
                            p(s) {
                              return s < 10 ? '0' + s : s
                            },
                        }
                     }) 
                     
                     $('.hide-date').each(function() {
                         let hideDateObj = $(this);
                         if ($.inArray(hideDateObj.html(),res.data.holidayDate) !== -1){
                             hideDateObj.parent().parent().parent().parent().find('.info-festival').append(res.data.holidaySign);
                         }
                     })
                },'json');
              })
              function commitData() {
                   var formData = new FormData($(\"[name='detailForm']\")[0]);
                    formData.append('holiday', JSON.stringify(window.app.date));
                                //异步提交数据
                    $.ajax({
                        url: root+'control/adIndex.html?cla=holiday&fun=detailEdit',
                        type: 'POST',
                        cache: false,
                        data: formData,
                        // 告诉jQuery不要去处理发送的数据
                        processData: false,
                        // 告诉jQuery不要去设置Content-Type请求头
                        contentType: false,
                        // beforeSend: function () {
                        //     console.log(\"正在进行，请稍候\");
                        // },
                        success: function (res) {
                            var data = JSON.parse(res);
                            if (data.warn === 2) {
                                if (data.href) {//如果异步返回的json参数中定义了重定向url，则跳转到本url
                                    window.location.href = data.href;
                                } else {
                                    window.location.reload();
                                }
                            } else {
                                warn(data.warn);
                            }
                        },
                        error: function (responseStr) {
                            console.log(responseStr);
                        }
                    });
              }
            </script>
           <style>
           .info-festival{font-size: 12px}
           
.obj{
  position: absolute;
  right: 10px;
  top: 10px;
  z-index: 9;
  font-size: 12px;
  color:
  #d2d2d2;
}
.calendar-pro__body table{border: 1px solid #bcdbff;}
            .calendar-pro__body table td .day-box{
                height: 43px;
            }
             .calendar-pro__body table td{
                text-align: center !important;
                padding: 0 !important;
                border: none;
             }
             .calendar-pro__body table th{
                text-align: center !important;
                padding: 3px !important;
             }
             .calendar-pro__body .select{
               border-radius:0;
             }
            
                /*****节假日**/
             .calendar-pro__body table td .day-box.select{
                 background-color: #bcdbff;
             }
             .calendar-pro.showWeek .weekend .info-date{color:#F73131 !important;}
             .calendar-pro.showWeek .weekend{background:unset}
                /*****在当月中显示的下个月的日期**/
             .calendar-pro__body table td .day-box.other-month-day{
               background-color: rgb(239, 239, 239);
               opacity: 0.1;
             }
               /*****在当月中显示的下个月的日期**/
             .calendar-pro__body table td .day-box.other-month-day .info-date{
               color: black;
             }
             .calendar-pro__body table td .info-date{
               font-size: 16px;
               font-weight: unset;
             }
             /*****周末**/
             .calendar-pro__body table td .day-box.today{
               outline: none !important;
             }
             #app ul li{
                 display:inline-block;
                 padding: 5px 8px;
             }
             .calendarD{
               width: 530px !important;
               height: 250px;
             }
             .dateTitle{
                 width: 100%;
                 text-align: center;
                 padding: 10px 0;
                 font-size: 20px;
             }
             .calendar-pro__body table td .day-box.select .info-date{color:black}
</style>
            ";
                $html = $this->tab($data);
            }
        }
        return $html;
    }
    public function setting()
    {
        $html = $this->layerEdit(array("table" => array(
            array(
                must . "开始日期：" => text(array('name' => 'holidayStart', 'laydate' => [], 'value' => $this->post('date'))),
            ),
            array(
                "结束日期：" => text(array('name' => 'holidayEnd', 'laydate' => [], 'value' => $this->post('date'))),
            ),
            array(
                must . '备注：' => text(array('name' => 'text', 'value' => $this->post('lunarFestival') ?: $this->post('festival')))
            )
        )));

        //返回弹出层
        return $this->layer(array("title" => "设置节假日", "height" => 280, "html" => $html));
    }

    public function settingEdit()
    {
        $id = $this->post('id');
        $startDate = $this->post('holidayStart');
        $endDate = $this->post('holidayEnd');
        $text = $this->post('text');
        $workDay = query(self::table, " id = '" . $id . "' ");
        //判断
       /* if (!$this->power(self::page, "edit")) {
            $json['warn'] = "权限不足";
        } else*/if (empty($workDay['id'])) {
            $json['warn'] = "未找到此节假日设置";
        } elseif (empty($startDate)) {
            $json['warn'] = "请选择开始日期";
        } elseif (!empty($endDate) && strtotime($endDate) < strtotime($startDate)) {
            $json['warn'] = "开始日期不能小于结束日期";
        } else {
            $holidays = json_decode($workDay['workDay'], true) ?: [];
            $festivals = json_decode($workDay['festival'], true) ?: [];
            $festivalDate = array_keys($festivals);
            $dt_start = strtotime($startDate);
            $dt_end = strtotime($endDate ?: $startDate);
            while ($dt_start <= $dt_end) {
                $today = date('Y-m-d',$dt_start);
                //判断当前日期是否有已在节假日中
                if (in_array($today, $festivalDate)) {
                    //周末
                    $festivals[$today]['text'] = $text;
                } else {
                    $festivals[$today] = [
                        'text' => $text
                    ];
                }
                //判断当前日期是否有已在节假日(含周末)中
                if (!in_array($today, $holidays)) {
                    $holidays[] = $today;
                }
                $dt_start = strtotime('+1 day', $dt_start);
            }
            $json['warn'] = update(array("table" => self::table, "field" => ['festival' => json_encode($festivals, 320),'workDay' => json_encode($holidays, 320)], "where" => "id = '$workDay[id]'"));
        }
        if (in_array($json['warn'], array("新增成功", "更新成功"))) {
            //添加日志
            $type = mb_substr($json['warn'], 0, 2, 'utf-8');
            $text =$type . "了节假日：" . $workDay['name'] . "；年份：{$workDay['year']}，备注：" . $workDay['text'];
            $this->logText(array("type" => self::page, "text" => $text));
            //返回
            $_SESSION['warn'] = $json['warn'];
            $json['warn'] = 2;
        }
        $json['href'] = root . "control/adIndex.html?cla=holiday&fun=detail&id=" . $id;
        return json_encode($json, 320);
    }

    public function getDay()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $json['data']['showDate'] = $info['workDay'] ? json_decode($info['workDay'], true) : [];
        $festivals = $info['festival'] ? json_decode($info['festival'], true) : [];
        $json['data']['holidayDate'] = array_keys($festivals);
        $monthArr = $titleArr = [];
        for ($i = 1; $i <= 12; $i++) {
            $monthArr[] = $info['year'] . '/' . sprintf("%02d", $i);
            $titleArr[] = $i . '月';
        }

        $json['data']['nowDate'] = $monthArr;
        $json['data']['dateTitle'] = $titleArr;
        $json['data']['holidaySign'] = <<<eof
<span style="color: #F73131;top:0;left:0;padding: 0 2px;position: absolute">休</span>
eof;

        return json_encode($json, 320);
    }

    /**
     * 添加当前年份所有非周末的日期
     */
    public function insertDay($year, $id)
    {
        $days = [];
        $dt_start = strtotime("{$year}-01-01");
        $dt_end = strtotime("{$year}-12-31");
        while ($dt_start <= $dt_end) {
            //判断当前是否是周末
            if ((date('w', $dt_start) == 6) || (date('w', $dt_start) == 0)) {
                //周末
                $days[] = date('Y-m-d', $dt_start);
            }
            $dt_start = strtotime('+1 day', $dt_start);
        }
        update(array('table' => self::table, 'field' => array('workDay' => json_encode($days, 320)), 'where' => " id = '$id'"));
    }


    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power = '';
        switch ($act) {
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }
    /*行政人事-节假日-批量删除*/
    public function delete()
    {
        $array = $this->post('workDayId') ?? $this->post('id');
        /*if (!$this->power(self::page, "del")) {
            $json['warn'] = "权限不足";
        } else*/if (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                //查询
                $workDay = query(self::table, " id = '$id' ");
                //删除节假日
                delete(array("table" => self::table, "where" => " id = '$id' "));
                //返回信息
                $text = "删除了节假日：" . $workDay['name'];
                $this->logText(array("type" => "workDay", "text" => $text));
                $x++;
            }
            $_SESSION['warn'] = "删除了" . $x . "个节假日";
            $json['warn'] = 2;
        }
        $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        return json_encode($json, 320);
    }
}


